'use strict';

var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');

/**
 * Throws a `Cancel` if cancellation has been requested.
 * 如果已请求取消，抛出' Cancel '
 */
function throwIfCancellationRequested(config) {
  if (config.cancelToken) {
    config.cancelToken.throwIfRequested();
  }
}

/**
 * Dispatch a request to the server using the configured adapter.
 * 使用配置的适配器将请求发送到服务器
 *
 * @param {object} config The config that is to be used for the request
 * @returns {Promise} The Promise to be fulfilled
 */
module.exports = function dispatchRequest(config) {
  throwIfCancellationRequested(config);

  // 最后一次整理config
  // Ensure headers exist
  config.headers = config.headers || {};

  // Transform request data
  config.data = transformData(
    config.data,
    config.headers,
    config.transformRequest  // transformRequest是
  );

  // Flatten headers
  config.headers = utils.merge(
    config.headers.common || {},
    config.headers[config.method] || {},
    config.headers
  );

  // 删除header属性里无用的属性
  utils.forEach(
    ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
    function cleanHeaderConfig(method) {
      delete config.headers[method];
    }
  );

  // 获取适配器，优先使用config上自定义的适配器(关于适配器可以参考defaults.js文件里的adapter)
  // 通过深入了解，发现adapter无论是引入xhr 还是 http 文件的，最后 返回的都是一个promise，所以adapter是一个promise
  var adapter = config.adapter || defaults.adapter;

  // 将整理后的config赋给适配器，并发起http请求
  return adapter(config).then(function onAdapterResolution(response) { // 请求成功
    throwIfCancellationRequested(config);

    // Transform response data  整理响应数据 并返回出去
    response.data = transformData(
      response.data,
      response.headers,
      config.transformResponse
    );

    return response;
  }, function onAdapterRejection(reason) {  // 请求失败
    if (!isCancel(reason)) {
      throwIfCancellationRequested(config);

      // Transform response data  整理响应数据
      if (reason && reason.response) {
        reason.response.data = transformData(
          reason.response.data,
          reason.response.headers,
          config.transformResponse
        );
      }
    }

    // 返回一个状态为失败的promise，reason为他的参数
    return Promise.reject(reason);
  });
};
